//
//  HNSH_CashierPayViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/26.
//

#import "HNSH_CashierPayViewController.h"
//M
#import "HNSH_ConfirmOrderModel.h"
#import "WXApi.h"
#import "HNSH_AlipayToors.h"
#import <SDPTLib/SDPTFramework.h>
//V
#import "HNSH_CashierPayHeader.h"
#import "HNSH_CashierPayCell.h"
#import "ST_PayPasswordView.h"
#import "AFNetworking.h"
//C
#import "HNSH_PaySuccessViewController.h"

NSString * const YiShanKEY1 = @"Xx52CDtWRH1etGu4IfFEB4OeRrnbr+EUd5VO7cBQFCqxfDl5FJcJaUjKJbHapVsyxSODBEbssNk=";

@interface HNSH_CashierPayViewController ()
@property (nonatomic, strong)HNSH_CashierPayHeader * headerView;
@property (nonatomic, copy)NSArray * dataArray;
@property (nonatomic, assign)NSInteger currentIndex;
@property (nonatomic, copy)NSString * token_id;

/* addBtn */
@property (nonatomic, strong) UIButton *payButton;

/* 银行卡支付 */
@property (nonatomic, assign) BOOL isBankPay;
/* trade_no */
@property (nonatomic, copy) NSString *trade_no;
@end

static NSString *HNSH_CashierPayCellID = @"HNSH_CashierPayCellID";

@implementation HNSH_CashierPayViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.isBankPay && [self.trade_no isNotBlank]) {
        [self yinHangPayStatus:self.trade_no];
    }
}

//MARK: Cycle Methods
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self showNavTitle:@"收银台" showLeftItem:YES];
    self.navView.backgroundColor = [UIColor appBGColor];
    
    self.isBankPay = NO;
    
    __weak typeof(self) weakSelf = self;
    self.navView.leftBlock = ^{
        if (weakSelf.navigationController.viewControllers.count >= 3) {
            if (weakSelf.fromAuth) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
                return;
            }
            [weakSelf.navigationController popToViewController:weakSelf.navigationController.viewControllers[weakSelf.navigationController.viewControllers.count-3] animated:YES];
        } else {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    };
    
    [self addObs];
    
    [self configTableView];
}

- (NSArray *)getDefaultData{
    NSArray * methods = self.payModel.methods;
    return methods;
}

- (void)addObs{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipaySuccess) name:@"kNotificationPaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryPayStatus) name:@"kNotificationPayCheck" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];

}

- (void)alipaySuccess{
    [self pushSuccessVC];
}

- (void)appBecomeActive {
    if (self.isBankPay && [self.trade_no isNotBlank]) {
        [self yinHangPayStatus:self.trade_no];
    }
}

//MARK: 购买商品
- (void)payOrderMoney {
    HNSH_CashierPayMethodItem * model = [self getSelModel];
    if ([model.type isEqualToString:@"APP_INTEGRAL"] ||         //积分
        [model.type isEqualToString:@"APP_MALL_GOLD"] ||        //金种子
        [model.type isEqualToString:@"APP_EXCHANGE_VALUE"] ||   //购物值
        [model.type isEqualToString:@"APP_BALANCE_BEAN"] ||     //汇豆
        [model.type isEqualToString:@"APP_BALANCE"]) {          //余额
        WeakSelf(weakSelf);
        [ST_PayPasswordView showPasswordViewWithSureBlock:^(NSString * _Nonnull password) {
            [weakSelf buyShopFromZZWithPassword:password type:model.type];
        } cancelBlock:^{
            
        }];
    } else {
        //现金支付
        [self buyShopFromCashWithType:model.type product_code:model.product_code];
    }
    
}

//MARK: 绿色种子购买
- (void)buyShopFromZZWithPassword:(NSString *)password type:(NSString *)type{
    [HNSH_ShopNetServer requestGoodsOrderPaymentWithOrderId:self.payModel.business_id pay_password:password success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self pushSuccessVC];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 现金购买
- (void)buyShopFromCashWithType:(NSString *)type product_code:(NSString *)product_code {
    [HNSH_ShopNetServer requestGoodsRechargeCreateWithPrice:self.payModel.amount business_id:self.payModel.business_id business_type:self.payModel.business_type channel_id:type product_code:product_code success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            self.isBankPay = YES;
            self.trade_no = [NSString stringWithFormat:@"%@",responseObject.resultset[@"trade_no"]];
            NSString *payment_data = [NSString stringWithFormat:@"%@",responseObject.resultset[@"payment_data"]];
            if ([type isEqualToString:@"ALIPAY_APP"] ||
                [type isEqualToString:@"MEIAOKEJI_PAY"]) {
                [self openZFBWithDic:responseObject.resultset];
            } else if ([type isEqualToString:@"WECHAT_APP"]) {
                [self openWXWithDic:responseObject.resultset];
            } else if ([type isEqualToString:@"SANDPAY"]) {
                [self sanPayWithDic:responseObject.resultset];
            } else if ([type isEqualToString:@"SIFANG_PAY"] ||
                       [type isEqualToString:@"HWGCM_PAY"] ||
                       [type isEqualToString:@"HUAWEIGU_PAY"]) {//银行卡-->进入网页
                ST_BaseWebController *web = [[ST_BaseWebController alloc]init];
                web.isClose = YES;
                web.titleString = @"支付";
                [web loadURLString:payment_data];
                [self.navigationController pushViewController:web animated:YES];
                return;
            } else if ([payment_data containsString:@"http"]) {
                ST_BaseWebController *web = [[ST_BaseWebController alloc]init];
                web.isClose = YES;
                web.titleString = @"支付";
                [web loadURLString:payment_data];
                [self.navigationController pushViewController:web animated:YES];
            } else {
                [self.view makeToast:@"暂无该支付方式"];
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)pushSuccessVC{
    HNSH_CashierPayMethodItem * model = [self getSelModel];
    HNSH_PaySuccessViewController * vc = [HNSH_PaySuccessViewController new];
    vc.fromWeb = self.fromWeb;
    vc.fromAuth = self.fromAuth;
    vc.typeStr = model.title;
    vc.priceStr = [NSString stringWithFormat:@"%@", self.payModel.amount_text];
    vc.hiddenOrder = self.hiddenOrder;
    [self.navigationController pushViewController:vc animated:YES];
}

//MARK:
- (HNSH_CashierPayMethodItem *)getSelModel{
    for (HNSH_CashierPayMethodItem * m in self.dataArray) {
        if (m.selected) {
            return m;
        }
    }
    return nil;
}

//MARK: 银行卡支付
- (void)yinHangPayStatus:(NSString *)orderId {
    [HNSH_ShopNetServer requestGoodsRechargeVerifyWithOrderId:orderId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self pushSuccessVC];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 打开微信
- (void)openWXWithDic:(NSDictionary *)resDic{
    PayReq * request = [[PayReq alloc] init];
    request.partnerId = resDic[@"partnerid"];
    request.prepayId = resDic[@"prepayid"];
    request.package = resDic[@"package"];
    request.nonceStr = resDic[@"noncestr"];
    request.timeStamp = (UInt32)[resDic[@"timestamp"] longLongValue];
    request.sign = resDic[@"sign"];
    [WXApi sendReq:request completion:nil];
}

//MARK: 调用支付宝
- (void)openZFBWithDic:(NSDictionary *)resDic{
    NSString * orderNo = resDic[@"payment_data"];
    WeakSelf(weakSelf);
    [[HNSH_AlipayToors shareToors] payOrderWithOrderString:orderNo complate:^(NSDictionary * _Nonnull resultDic) {
        [weakSelf processingAliPayResultData:resultDic];
    }];
}

/** 处理支付结果*/
- (void)processingAliPayResultData:(NSDictionary *)resultDict {
    NSString *resultStatus = [NSString stringWithFormat:@"%@", resultDict[@"resultStatus"]];
    if (![resultStatus isNotBlank]) {
        return;
    }
    NSInteger status = [resultStatus integerValue];
    switch (status) {
        case 9000:{
            //订单支付成功
            [self pushSuccessVC];
            break;
        }
        case 8000:{
            //正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
            [self.view makeToast:@"正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态"];
            break;
        }
        case 4000:{
            //订单支付失败
            [self.view makeToast:@"订单支付失败"];
            break;
        }
        case 5000:{
            //重复请求
            [self.view makeToast:@"重复请求"];
            break;
        }
        case 6001:{
            //用户中途取消
            [self.view makeToast:@"用户中途取消"];
            break;
        }
        case 6002:{
            //网络连接出错
            [self.view makeToast:@"网络连接出错"];
            break;
        }
        case 6004:{
            //支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
            [self.view makeToast:@"支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态"];
            break;
        }
        default:{
            //其它支付错误
            [self.view makeToast:@"其它支付错误"];
            break;
        }
    }
}

//MARK: 杉德支付
- (void)sanPayWithDic:(NSDictionary *)resString{
    NSDictionary * resDic = [resString[@"payment_data"] jsonValueDecoded];
    XHPayParameterModel *model = [XHPayParameterModel yy_modelWithDictionary:resDic];
    
    [[SDPTController shared] showSDPTDesktopIn:self model:model];
    
    // 支付成功 回调
    [SDPTController shared].paySucTypeBlock = ^(ProductPyType type, id  _Nonnull responseObj) {
        
        if (type ==PyTypeUnionQuick) {
            NSLog(@"支付类型快捷充值 支付 成功 -  -- - 商户自己定义的标记字符串 : %@",(NSString*)responseObj);
        }
        if (type ==PyTypeUnionPHFive) {
            NSLog(@"支付类型银联WAP 支付 成功 -  -- - 商户自己定义的标记字符串 : %@",(NSString*)responseObj);
        }
        if (type == PyTypeUnionPFast) {
            NSLog(@"支付类型银联快捷 支付 成功 -  -- - 商户自己定义的标记字符串 : %@",(NSString*)responseObj);
            NSLog(@"商户根据自己定义的标记字符串 跳转不同的页面");
        }
        
    };
    
    ///  用户点击左边返回按钮 取消回调
    [SDPTController shared].backBtnActionPayPageDismissBlock = ^{
        NSLog(@"银联快捷 用户点击 支付页面消失");
    };
    
    [SDPTController shared].payFailureBlock = ^(ProductPyType type, NSString * _Nonnull errorMsg) {
        NSLog(@"调取单个 支付  错误 信息 -- 错误类型 - type - %ld -  - - errorMsg- - -%@",type,errorMsg);
        /// SDK 返回失败回调中 做用户友好交互处理
    };
}

//MARK: 唤起微信小程序支付
- (void)selectWxPay:(NSString *)tokenID{
    NSString * allPath = [NSString stringWithFormat:@"pages/zf/index?token_id=%@",tokenID];
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = @"gh_65f1d3a5707f";
    launchMiniProgramReq.path = allPath;
    launchMiniProgramReq.miniProgramType = 0;
    [WXApi sendReq:launchMiniProgramReq completion:nil];
}

//MARK: 支付宝支付结果查询
- (void)queryPayStatus{
    if (!self.token_id.length) {
        return;
    }
    NSString * strjson = @"https://sandcash.mixienet.com.cn/gateway/api/query/";
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    NSDictionary * paramter = @{@"token_id":self.token_id};
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [manager POST:strjson parameters:paramter headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"ret_code"] isEqual:@"000000"]) {
            [self pushSuccessVC];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

//MARK: Getter Methods

- (HNSH_CashierPayHeader *)headerView{
    if (!_headerView) {
        _headerView = [[HNSH_CashierPayHeader alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 178)];
        _headerView.model = self.payModel;
    }
    return _headerView;
}

- (UIButton *)payButton{
    if (!_payButton) {
        _payButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _payButton.frame = CGRectMake(30, kScreenHeight - 50 - 23 - kBottomSafeHeight, kScreenWidth - 60, 50);
        [_payButton setTitle:@"" forState:UIControlStateNormal];
        [_payButton setTitleColor:[UIColor appWhiteLabelColor] forState:UIControlStateNormal];
        _payButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        _payButton.backgroundColor = [UIColor appGreenColor];
        _payButton.layer.cornerRadius = 25;
        _payButton.layer.masksToBounds = YES;
        [_payButton addTarget:self action:@selector(payOrderMoney) forControlEvents:UIControlEventTouchUpInside];
    }
    return _payButton;
}

- (NSArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [self getDefaultData];
    }
    return _dataArray;
}

- (void)configTableView {
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(kNavBarAndStatusBarHeight, 0, 50 + 46 + kBottomSafeHeight, 0));
    }];
    
    self.tableView.rowHeight = 77;
    [self.tableView registerClass:[HNSH_CashierPayCell class] forCellReuseIdentifier:HNSH_CashierPayCellID];
    
    self.tableView.tableHeaderView = self.headerView;
   
    HNSH_CashierPayMethodItem * m = [self getSelModel];
    [self.view addSubview:self.payButton];
    [self.payButton setTitle:m.button_text forState:UIControlStateNormal];
}

//MARK: UITableViewDelegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HNSH_CashierPayCell * cell = [tableView dequeueReusableCellWithIdentifier:HNSH_CashierPayCellID];
    HNSH_CashierPayMethodItem * model = self.dataArray[indexPath.row];
    cell.model = model;
    if (model.selected) {
        cell.isSelected = YES;
    } else {
        cell.isSelected = NO;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self setDefault];
    HNSH_CashierPayMethodItem * model = self.dataArray[indexPath.row];
    model.selected = YES;
    [self.payButton setTitle:model.button_text forState:UIControlStateNormal];
    [self.tableView reloadData];
}

- (void)setDefault{
    for (HNSH_CashierPayMethodItem * m in self.dataArray) {
        m.selected = NO;
    }
}

@end
